#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void swap(int arr[], int x, int y)
{
	int tmp = arr[x];
	arr[x] = arr[y];
	arr[y] = tmp;
}
void ShelltSort(int arr[], int sz)
{
	int gap = sz;
	while (gap > 1)
	{
		gap /= 2;
		for (int i = gap; i < sz; i++)
		{
			for (int j = i; j >= gap && arr[j] < arr[j - gap]; j-=gap)
			{
				swap(arr, j, j - gap);
			}
		}
	}
}
void MergeSort(int arr[], int left, int right)
{
	if (left >= right)
		return;
	int mid = left + (right - left) / 2;
	MergeSort(arr, left, mid);
	MergeSort(arr, mid + 1, right);
	int* help = (int*)malloc(sizeof(int) * (left - right + 1));
	int cur1 = left;
	int cur2 = right;
	int index = 0;
	while (cur1 <= mid && cur2 <= right)
	{
		help[index++] = arr[cur1] <= arr[cur2] ? arr[cur1++] : arr[cur2++];
	}
	while (cur1 <= mid)
	{
		help[index++] = arr[cur1++];
	}
	while (cur2 <= mid)
	{
		help[index++] = arr[cur2++];
	}
	for (int i = 0; i < sz; i++)
	{

	}
}

void MergeSortNonR(int arr[], int sz)
{
	int gap = 1;
	int* help = (int*)malloc(sizeof(int) * sz);
	memset(help, 0, sizeof(int) * sz);
	while (gap < sz)
	{
		for (int i = 0; i < sz; i += 2*gap)
		{
			int index = i;
			int begin1 = i;
			int end1 = begin1 + gap - 1;
			int begin2 = end1 + 1;
			int end2 = begin2 + gap - 1;
			if(begin2 >= sz)
				break;
			if(end2 >= sz)
				end2 = sz - 1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				help[index++] = arr[begin1] <= arr[begin2] ? arr[begin1++] : arr[begin2++];
			}
			while (begin1 <= end1)
			{
				help[index++] = arr[begin1++];
			}
			while (begin2 <= end2)
			{
				help[index++] = arr[begin2++];
			}
			memcpy(arr + i, help + i, sizeof(int) * (end2 - i + 1));
		}
		gap *= 2;
	}
	free(help);
}

int main()
{
	int arr[] = { 5,2,1,4,3 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	MergeSortNonR(arr, sz);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}